package com.qms.qep.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qms.qep.mapper.DefectMapper;
import com.qms.qep.domain.Defect;
import com.qms.qep.service.IDefectService;
import com.qms.common.exception.ServiceException;

/**
 * 缺陷类型Service业务层处理
 */
@Service
public class DefectServiceImpl implements IDefectService {
    @Autowired
    private DefectMapper defectMapper;

    /**
     * 查询缺陷类型
     * 
     * @param id 缺陷类型主键
     * @return 缺陷类型
     */
    @Override
    public Defect selectDefectById(Integer id) {
        return defectMapper.selectDefectById(id);
    }

    /**
     * 查询缺陷类型列表
     * 
     * @param defect 缺陷类型
     * @return 缺陷类型
     */
    @Override
    public List<Defect> selectDefectList(Defect defect) {
        return defectMapper.selectDefectList(defect);
    }
    
    /**
     * 查询缺陷类型树结构
     * 
     * @param defect 缺陷类型
     * @return 缺陷类型树
     */
    @Override
    public List<Defect> selectDefectTree(Defect defect) {
        return defectMapper.selectDefectTree(defect);
    }

    /**
     * 新增缺陷类型
     * 
     * @param defect 缺陷类型
     * @return 结果
     */
    @Override
    public int insertDefect(Defect defect) {
        // 设置默认值
        if (defect.getStatus() == null) {
            defect.setStatus(1);
        }
        // 如果没有设置排序号，则设置为最大值+1
        if (defect.getOrderNum() == null) {
            defect.setOrderNum(1);
        }
        return defectMapper.insertDefect(defect);
    }

    /**
     * 修改缺陷类型
     * 
     * @param defect 缺陷类型
     * @return 结果
     */
    @Override
    public int updateDefect(Defect defect) {
        return defectMapper.updateDefect(defect);
    }

    /**
     * 批量删除缺陷类型
     * 
     * @param ids 需要删除的缺陷类型主键
     * @return 结果
     */
    @Override
    public int deleteDefectByIds(Integer[] ids) {
        // 检查是否存在子缺陷
        for (Integer id : ids) {
            if (defectMapper.checkDefectExistChild(id) > 0) {
                Defect defect = defectMapper.selectDefectById(id);
                throw new ServiceException(String.format("%1$s存在子缺陷,不能删除", defect.getName()));
            }
        }
        return defectMapper.deleteDefectByIds(ids);
    }

    /**
     * 删除缺陷类型信息
     * 
     * @param id 缺陷类型主键
     * @return 结果
     */
    @Override
    public int deleteDefectById(Integer id) {
        // 检查是否存在子缺陷
        if (defectMapper.checkDefectExistChild(id) > 0) {
            Defect defect = defectMapper.selectDefectById(id);
            throw new ServiceException(String.format("%1$s存在子缺陷,不能删除", defect.getName()));
        }
        return defectMapper.deleteDefectById(id);
    }
} 